package com.jsmile.cloud.accountcenter.account.repo;

import java.util.Objects;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsmile.cloud.accountcenter.account.dao.MemberDao;
import com.jsmile.cloud.accountcenter.account.model.Member;
import com.jsmile.cloud.accountcenter.api.req.account.ReqMemberQuery;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年06月04日 04:38:37
 */
@Service
@Slf4j
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class MemberSearchRepository extends ServiceImpl<MemberDao, Member> {

    public Member findOneByUserIdAndTenantId(Long userId, Long tenantId) {
        return this.baseMapper.findOneByUserIdAndTenantId(userId, tenantId);
    }

    public IPage<Member> pageQuery(ReqMemberQuery reqMemberQuery) {
        return this.baseMapper.selectPage(reqMemberQuery.getPage(), getQueryWrapper(reqMemberQuery));
    }

    private Wrapper getQueryWrapper(ReqMemberQuery reqMemberQuery) {
        return new QueryWrapper<Member>().lambda().eq(Member::getTenantId, reqMemberQuery.getCurTenantId())
            .eq(null != reqMemberQuery.getShopId(), Member::getShopId, reqMemberQuery.getShopId())
            .eq(null != reqMemberQuery.getUserId(), Member::getShopId, reqMemberQuery.getUserId())
            .eq(Objects.nonNull(reqMemberQuery.getOpenId()), Member::getOpenId, reqMemberQuery.getOpenId())
            .eq(Objects.nonNull(reqMemberQuery.getAppOpenId()), Member::getAppOpenId, reqMemberQuery.getAppOpenId())
            .eq(null != reqMemberQuery.getFansLeader(), Member::getShopId, reqMemberQuery.getFansLeader())
            .eq(null != reqMemberQuery.getMemberCode(), Member::getMemberCode, reqMemberQuery.getMemberCode())
            .like(Objects.nonNull(reqMemberQuery.getName()), Member::getName, reqMemberQuery.getName())
            .like(Objects.nonNull(reqMemberQuery.getCity()), Member::getCity, reqMemberQuery.getCity())
            .ge(null != reqMemberQuery.getStartDate(), Member::getCreateTime, reqMemberQuery.getStartDate())
            .le(null != reqMemberQuery.getEndDate(), Member::getCreateTime, reqMemberQuery.getEndDate())
            .ge(null != reqMemberQuery.getStartTime(), Member::getCreateTime, reqMemberQuery.getStartTime())
            .le(null != reqMemberQuery.getEndTime(), Member::getCreateTime, reqMemberQuery.getEndTime())
            .like(Objects.nonNull(reqMemberQuery.getProvince()), Member::getProvince, reqMemberQuery.getProvince()).orderByDesc(Member::getUpdateTime);// sort,createTime倒序
    }
}
